import api from '../api/api'
import tip from './tip'

  // 通过商品编码或属性编码或SKU编码获取商品信息
  async function getItemsList(itemsData,merchantInfo,type) {
    let that = this;
    var isValid = 1;

    if (itemsData.showNoStock == 1) {
      isValid = 0;
    } else {
      isValid = 1;
    }

    if(!itemsData.inputItems){
     return
    }else{
      // 获取商品列表
       const json = await api.getGoodsListNew({
         query: {
           q: itemsData.inputItems,
           page_no: 1,
           page_size: 30,
           merchant_id: merchantInfo.cloudMerchantId,
           store_id: merchantInfo.cloudMerchantStoreId,
           is_valid: isValid,
      		   after_page: ''
         }
       });
       if (json.code === 1000) {
         if (json.data.content.length > 0) {
           var itemsListArr = json.data;
           itemsListArr.showType = itemsData.showType ? itemsData.showType : 'vertical';
           itemsListArr.inputItems = itemsData.inputItems;    //商品编码
           itemsListArr.showNoStock = itemsData.showNoStock;  //是否显示0库存
           itemsListArr.width = itemsData.width;              //宽度
           itemsListArr.showItemName = itemsData.showItemName ? itemsData.showItemName : "1"; //是否显示名称
           itemsListArr.showItemBlock = itemsData.showItemBlock ? itemsData.showItemBlock : "1"; //是否显示色块
           itemsListArr.showItemPrice = itemsData.showItemPrice ? itemsData.showItemPrice : "1"; //是否显示价格
           itemsListArr.showMajorUrl = itemsData.showMajorUrl ?  itemsData.showMajorUrl : "1"; //显示主图还是副图

           var itemsList = itemsListArr.content;

           // 策略价格
           var s_item = [];
           for (var i in itemsList) {
             s_item = itemsList[i];
             var strategyIdArr = [];
             for (var j in s_item['strategies']) {
               var s_strategy = s_item['strategies'][j]
               if (s_strategy['strategyStartTime'] != '' && s_strategy['strategyStartTime'] != '' && s_strategy[
                   'strategyEndTime'] != null && s_strategy['strategyEndTime'] != null &&
                 s_strategy['strategyPrice'] != null && s_strategy['strategyPrice'] != '' && Number(s_strategy[
                   'strategyPrice']) > 0) {
                 var endTimestamp = Date.parse(s_strategy['strategyEndTime'].replace(/-/g, '/')); // 为了兼容IOS，需先将字符串转换为'2018/9/11 9:11:23' 返回'2018-9-12 9:11:23'的时间戳
                 var startTimestamp = Date.parse(s_strategy['strategyStartTime'].replace(/-/g, '/'));
                 var timestamp = (new Date()).getTime();
                 if (timestamp >= startTimestamp && timestamp < endTimestamp) {
                   strategyIdArr.push(s_strategy)
                 } else {

                 }
               }
             }
             if (strategyIdArr != '') {
               s_item['price'] = strategyIdArr[0].strategyPrice;
             }
           }
           return itemsListArr
         }
       } else {
         tip.plainText(json.data.msg);
       }
    }

  }


  // 根据cid获取商品列表
  async function getItemList(itemData,merchantInfo,type) {
    // 获取商品列表
    let that = this;
    var isValid = 1; // 不展示0库存商品

    if (itemData.showNoStock == 1) {
      isValid = 0;
    } else {
      isValid = 1;
    }

    if(!itemData.cid){
      return
    }else{
      const json = await api.getGoodsListNew({
        query: {
          class_id: itemData.cid || '',
          page_no: 1,
          page_size: itemData.count || 12,
      	  merchant_id: merchantInfo.cloudMerchantId,
      	  store_id: merchantInfo.cloudMerchantStoreId,
          is_valid: isValid,
      		  after_page: ''
        }
      });

      if (json.code === 1000) {
        var categoryListArr = json.data;
            categoryListArr.categoryTitle = itemData.categoryTitle || itemData.label;
            categoryListArr.showType = itemData.showType ? itemData.showType : 'vertical';
            categoryListArr.width = itemData.width;
            categoryListArr.cid = itemData.cid;
            categoryListArr.count = itemData.count;
            categoryListArr.showItemName = itemData.showItemName ? itemData.showItemName : "1"; //是否显示名称
            categoryListArr.showItemBlock = itemData.showItemBlock ? itemData.showItemBlock : "1"; //是否显示色块
            categoryListArr.showItemPrice = itemData.showItemPrice ? itemData.showItemPrice : "1"; //是否显示价格
            categoryListArr.showMajorUrl = itemData.showMajorUrl ?  itemData.showMajorUrl : "1"; //显示主图还是副图
        var categoryList = categoryListArr.content;
        // 策略价格
        var s_item = [];
        for (var i in categoryList) {
          s_item = categoryList[i];

         if(type == 'items_change'){
           categoryList[i].width = 50
           categoryList[0].width = 100;
         }

          var strategyIdArr = [];
          for (var j in s_item['strategies']) {
            var s_strategy = s_item['strategies'][j]
            if (s_strategy['strategyStartTime'] != '' && s_strategy['strategyStartTime'] != '' && s_strategy[
                'strategyEndTime'] != null && s_strategy['strategyEndTime'] != null &&
              s_strategy['strategyPrice'] != null && s_strategy['strategyPrice'] != '' && Number(s_strategy[
                'strategyPrice']) > 0) {
              var endTimestamp = Date.parse(s_strategy['strategyEndTime'].replace(/-/g, '/')); // 为了兼容IOS，需先将字符串转换为'2018/9/11 9:11:23' 返回'2018-9-12 9:11:23'的时间戳
              var startTimestamp = Date.parse(s_strategy['strategyStartTime'].replace(/-/g, '/'));
              var timestamp = (new Date()).getTime();
              if (timestamp >= startTimestamp && timestamp < endTimestamp) {
                strategyIdArr.push(s_strategy)
              } else {}
            }
          }
          if (strategyIdArr != '') {
            s_item['price'] = strategyIdArr[0].strategyPrice;
          }
        }

        return categoryListArr
      } else {
        tip.plainText(json.data.msg);
      }
    }

  }

  // 根据cid 或者 商品编码 获取商品列表 items_change
  async function getItemsListTab(tabsData,merchantInfo) {
    // 获取商品列表
    let that = this;
    let cid = '';
    let inputItems = '';
    let customerInfo = uni.getStorageSync('customerInfo');
    let memberDetails = uni.getStorageSync('memberDetails') || getApp().globalData.memberDetails
    if(tabsData.cid && tabsData.type == 'category'){
      cid = tabsData.cid;
    }else if(tabsData.type == 'goods'){
      inputItems = tabsData.inputItems;
    }

    var tabsDataJson = [];
      tabsDataJson = tabsData;
    const json = await api.getGoodsListNew({
      query: {
        q: inputItems,
        class_id: cid || '',
        page_no: 1,
        page_size: tabsData.count || 12,
        merchant_id: merchantInfo.cloudMerchantId,
        store_id: merchantInfo.cloudMerchantStoreId,
        group_id: !!memberDetails ? memberDetails.customerGroupId : 0,
        member_level_id: !!memberDetails ? memberDetails.memberLevelId : 0,
        member_status: !!memberDetails ? memberDetails.isActive : 'Inactive',
        after_page: ''
      }
    });
    if (json.code === 1000) {
      var categoryListArr = json.data;
        tabsDataJson.content = categoryListArr.content;
      var categoryList = tabsDataJson.content;
      // 策略价格
      var s_item = [];
      var tabsContent = [];
      for (var i in categoryList) {
        s_item = categoryList[i];
        if(!!categoryList[i].strategies) {
    		that.$commonFunction.priceRulesDeal(categoryList[i].strategies).then(res => {
    			if(res.price !== 0) {
    			  categoryList[i].price = res.price
    			}
    			if(res.rulesArr.length > 0) {
    			  categoryList[i].rulesArr = res.rulesArr
    			}
    		  })
        }

        // 促销
        if (s_item.promotionTagList) {
          let promotionTag = s_item.promotionTagList;
          if (promotionTag.length > 1) {
            for (let k = 0; k < promotionTag.length - 1; k++) {
              promotionTag[k].promotionTag = promotionTag[k].promotionTag + "，";
            }
          }
        }

      }

      if(tabsDataJson.isBig == 1){
        tabsContent = tabsDataJson.content[0];
        tabsContent.width = '100';
      }
      return tabsDataJson
    } else {
      tip.plainText(json.data.msg);
    }
  }

  /**
   * CMS配置页面 转发背景图
   */
  async function getCMSPageInfo(identifier) {
    let merchantInfo = uni.getStorageSync('merchantInfo');
    let that = this;
    let mt = '1.0';
    let jwt = '';
    const json = await api.getConfigDetail({
      method: 'POST',
      header: {
        'jwt': jwt
      },
      query: {
        "identifier": identifier,
        "merchantId": merchantInfo.cloudMerchantId,
        "storeId": merchantInfo.cloudMerchantStoreId,
        "mt": mt
      }
    });
    if (json.data.code === 1000 && json.data.data !== null) {
      let configData = json.data.data;
      let cmsConfigData = {};
      if (this.preview) {
        cmsConfigData = JSON.parse(configData.preview);
      } else {
        cmsConfigData = JSON.parse(configData.content)
        let contents = configData.contents;
        for (let index in contents) {
          let startTime = contents[index].startTime;
          startTime = startTime.substring(0, 19);
          startTime = startTime.replace(/-/g, '/');
          let startTimeTimestamp = new Date(startTime).getTime();
          if (startTimeTimestamp <= new Date().getTime()) {
            cmsConfigData = JSON.parse(contents[index].content);
            break;
          }
        }
      }
      let CMSItembanner = cmsConfigData,
         CMSItembannerImage = cmsConfigData[0];
      let CMSInfo = {
        shareImage: CMSItembannerImage[0].data.src,
        shareTitle: CMSItembannerImage[0].data.title
      }
      return CMSInfo;
    }
  }


module.exports = {
  getItemsList:getItemsList,
  getItemList:getItemList,
  getItemsListTab: getItemsListTab,
  getCMSPageInfo:getCMSPageInfo
}
